package pri.damai.xiaowu.common.core.filter;

import cn.hutool.core.util.URLUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import pri.damai.xiaowu.common.core.constant.HttpHeaderKeyConstant;
import pri.damai.xiaowu.common.core.model.ThreadLocalUserInfo;
import pri.damai.xiaowu.common.core.util.LocalUserUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *
 * @Desc
 * @Author DaMai
 * @Date 2021/5/19 15:57
 * 但行好事，莫问前程。
 */
@Slf4j
public class ThreadLocalUserFilter implements Filter {

    public static final String FILTER_NAME = "threadLocalUserFilter";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        // 从请求头中取出用户数据
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String userId = request.getHeader(HttpHeaderKeyConstant.USER_ID_KEY);
        if (StringUtils.isBlank(userId)) {
            log.warn("请求头中未获取到 userId。");
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        String orgId = request.getHeader(HttpHeaderKeyConstant.ORG_ID_KEY);
        String userName = request.getHeader(HttpHeaderKeyConstant.USER_NAME_KEY);
        String orgName = request.getHeader(HttpHeaderKeyConstant.ORG_NAME_KEY);

        // 放到线程变量中
        ThreadLocalUserInfo info = new ThreadLocalUserInfo();
        info.setUserId(Long.parseLong(userId))
                .setOrgId(Long.parseLong(orgId))
                .setOrgName(urlDecode(orgName))
                .setUsername(urlDecode(userName));
        log.debug("线程用户:{}", info);
        LocalUserUtils.setLocalUser(info);
        filterChain.doFilter(servletRequest, servletResponse);
    }

    private String urlDecode(String param) {
        if (StringUtils.isBlank(param)) {
            return param;
        }
        return URLUtil.decode(param);
    }
}
